﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Text;

namespace Common
{
    public class OledbHelper
    {
        private static string path = Path.GetDirectoryName(Path.GetDirectoryName(HttpContext.Current.Server.MapPath("/")));
        public static string sqlConnString =
            ConfigurationManager.ConnectionStrings["mdbConnection"].ConnectionString.ToString() + path +
            "\\" + ConfigurationManager.AppSettings["dbPath"].ToString();

        //public static string sqlConnString =
        //    ConfigurationManager.ConnectionStrings["mdbConnection"].ConnectionString.ToString() +
        //    HttpContext.Current.Server.MapPath("\\") + ConfigurationManager.AppSettings["dbPath"].ToString();

        #region 公用方法
        /// <summary>
        /// 获取ID最大值
        /// </summary>
        /// <param name="FieldName">字段</param>
        /// <param name="TableName">表</param>
        /// <returns>返回ID最大值</returns>
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        /// <summary>
        /// 检查数据库连接
        /// </summary>
        /// <returns>返回连接状态</returns>
        public static string CheckConn()
        {
            try
            {
                using (OleDbConnection conn = new OleDbConnection(sqlConnString))
                {
                    conn.Open();
                    return "连接数据库成功";
                }
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        /// <summary>
        /// 检查数据库连接
        /// </summary>
        /// <returns>返回是否</returns>
        public static bool isConn()
        {
            try
            {
                using (OleDbConnection conn = new OleDbConnection(sqlConnString))
                {
                    conn.Open();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <returns>返回是否</returns>
        public static bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <param name="cmdParms">SQL参数</param>
        /// <returns>返回是否</returns>
        public static bool Exists(string strSql, params OleDbParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                return false;
            }
            else
            {
                return int.Parse(obj.ToString()) > 0 ? true : false;
            }
        }
        #endregion

        #region 公用简单sql方法
        /// <summary>
        /// 执行sql语句，返回影响的记录数
        /// </summary>
        /// <param name="sqlString">sql语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string sqlString)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                using (OleDbCommand cmd = new OleDbCommand(sqlString, conn))
                {
                    try
                    {
                        conn.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (OleDbException ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行sql语句，返回影响的记录数
        /// </summary>
        /// <param name="sqlString">sql语句</param>
        /// <param name="times">获取或设置在终止执行命令的尝试并生成错误之前的等待时间（以秒为单位）</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSqlByTimes(string sqlString, int times)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                using (OleDbCommand cmd = new OleDbCommand(sqlString, conn))
                {
                    try
                    {
                        conn.Open();
                        cmd.CommandTimeout = times;     //默认值为 30 秒, 0 指示无限制。
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (OleDbException ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>
        /// <returns>影响记录数</returns>
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                conn.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = conn;
                OleDbTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }

        /// <summary>
        /// 执行sql语句，返回OleDbDataReader ( 注意：调用该方法后，一定要对OleDbDataReader进行Close )
        /// </summary>
        /// <param name="sqlString">sql语句</param>
        /// <returns>OleDbDataReader</returns>
        public static OleDbDataReader ExecuteReader(string sqlString)
        {
            OleDbConnection conn = new OleDbConnection(sqlConnString);
            OleDbCommand cmd = new OleDbCommand(sqlString, conn);
            try
            {
                conn.Open();
                OleDbDataReader sdr = cmd.ExecuteReader();
                return sdr;
            }
            catch (OleDbException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 执行sql语句，返回DataSet
        /// </summary>
        /// <param name="sqlString">sql语句</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecuteDataSet(string sqlString)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                using (OleDbDataAdapter sda = new OleDbDataAdapter(sqlString, conn))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        conn.Open();
                        sda.Fill(ds, "ds");
                        return ds;
                    }
                    catch (OleDbException ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行sql语句，返回DataSet
        /// </summary>
        /// <param name="sqlString">sql语句</param>
        /// <param name="times">获取或设置在终止执行命令的尝试并生成错误之前的等待时间（以秒为单位）</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecuteDataSetByTimes(string sqlString, int times)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                using (OleDbDataAdapter sda = new OleDbDataAdapter(sqlString, conn))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        conn.Open();
                        sda.SelectCommand.CommandTimeout = times;
                        sda.Fill(ds, "ds");
                        return ds;
                    }
                    catch (OleDbException ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        public static int ExecuteGetCount(string sqlString)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                conn.Open();
                using (OleDbDataReader sdr = new OleDbDataAdapter(sqlString, conn).SelectCommand.ExecuteReader())
                {
                    try
                    {
                        if (sdr.Read())
                        {
                            return int.Parse(sdr[0].ToString());
                        }
                        else
                        {
                            return 0;
                        }
                    }
                    catch (OleDbException ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {

            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                DataSet ds = new DataSet();
                try
                {
                    conn.Open();
                    OleDbDataAdapter command = new OleDbDataAdapter(SQLString, conn);
                    command.Fill(ds, "ds");
                }
                catch (OleDbException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }

        }

        /// <summary>
        ///  执行带参数的查询SQL语句或存储过程
        /// </summary>
        /// <param name="cmdText">查询SQL语句或存储过程</param>
        /// <param name="paras">参数集合</param>
        /// <returns></returns>
        public static DataTable ExecuteQuery(string sqlString)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                conn.Open();
                using (OleDbDataReader dr = new OleDbCommand(sqlString, conn).ExecuteReader(CommandBehavior.CloseConnection))
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        dt.Load(dr);
                        return dt;
                    }
                    catch (OleDbException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }
        }
        #endregion

        #region 公用带参数sql方法
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string sqlString, OleDbParameter[] sqlParms)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, conn, null, sqlString, sqlParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (OleDbException ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行sql语句，返回OleDbDataReader ( 注意：调用该方法后，一定要对OleDbDataReader进行Close )
        /// </summary>
        /// <param name="strSQL">sql语句</param>
        /// <param name="sqlParms">sql参数</param>
        /// <returns>OleDbDataReader</returns>
        public static OleDbDataReader ExecuteReader(string sqlString, params OleDbParameter[] sqlParms)
        {
            OleDbConnection conn = new OleDbConnection(sqlConnString);
            OleDbCommand cmd = new OleDbCommand();
            try
            {
                PrepareCommand(cmd, conn, null, sqlString, sqlParms);
                OleDbDataReader sDr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return sDr;
            }
            catch (OleDbException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 执行sql语句，返回DataSet
        /// </summary>
        /// <param name="sqlString">sql语句</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecuteDataSet(string sqlString, params OleDbParameter[] sqlParms)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                OleDbCommand cmd = new OleDbCommand();
                PrepareCommand(cmd, conn, null, sqlString, sqlParms);
                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                        return ds;
                    }
                    catch (OleDbException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }
        }

        /// <summary>
        ///  执行带参数的查询SQL语句或存储过程
        /// </summary>
        /// <param name="cmdText">查询SQL语句或存储过程</param>
        /// <param name="paras">参数集合</param>
        /// <returns></returns>
        public static DataTable ExecuteQuery(string sqlString, OleDbParameter[] sqlParms)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                OleDbCommand cmd = new OleDbCommand();
                PrepareCommand(cmd, conn, null, sqlString, sqlParms);
                using (OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    DataTable dt = new DataTable();
                    try
                    {
                        dt.Load(dr);
                        cmd.Parameters.Clear();
                        return dt;
                    }
                    catch (OleDbException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 准备OleDbCommand
        /// </summary>
        /// <param name="cmd">OleDbCommand(命令)</param>
        /// <param name="conn">OleDbConnection(连接)</param>
        /// <param name="trans">OleDbTransaction(事务)</param>
        /// <param name="cmdText">Sql语句</param>
        /// <param name="cmdParms">OleDbParameter(参数)</param>
        private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, string cmdText, OleDbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (OleDbParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString, params OleDbParameter[] cmdParms)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, conn, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (OleDbException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params OleDbParameter[] cmdParms)
        {
            using (OleDbConnection connection = new OleDbConnection(sqlConnString))
            {
                OleDbCommand cmd = new OleDbCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (OleDbException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }

        }
        #endregion

        #region 公用存储过程操作
        /// <summary>
        /// 执行存储过程，返回OleDbDataReader ( 注意：调用该方法后，一定要对OleDbDataReader进行Close )
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OleDbDataReader</returns>
        public static OleDbDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            OleDbConnection conn = new OleDbConnection(sqlConnString);
            OleDbDataReader returnReader;
            conn.Open();
            OleDbCommand command = BuildQueryCommand(conn, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
            return returnReader;

        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (OleDbConnection conn = new OleDbConnection(sqlConnString))
            {
                DataSet dataSet = new DataSet();
                conn.Open();
                OleDbDataAdapter sqlDA = new OleDbDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(conn, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                conn.Close();
                return dataSet;
            }
        }

        /// <summary>
        /// 构建 OleDbCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OleDbCommand</returns>
        private static OleDbCommand BuildQueryCommand(OleDbConnection conn, string storedProcName, IDataParameter[] parameters)
        {
            OleDbCommand command = new OleDbCommand(storedProcName, conn);
            command.CommandType = CommandType.StoredProcedure;
            foreach (OleDbParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }
        #endregion
    }
}
